import 'dart:async';
import 'dart:isolate';

import 'package:flutter/material.dart';
import 'package:we_chat/pages/const.dart';
import '../../tools/http_manager.dart' as http;
//as 用于解决方法名冲突的问题.重命名
// import 'package:http/http.dart' as http;
//hide 隐藏某个不要导入的方法
//show 只导入某些内容
import 'dart:convert';
import 'package:we_chat/pages/chat/search_bar.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({Key? key}) : super(key: key);

  @override
  State<ChatPage> createState() => _ChatPageState();
}

int count = 0;


/*
* 保持状态
* 1。混入 AutomaticKeepAliveClientMixin
* 2。重写 get方法
* 3。build调用 super.build(context);方法
* */
class _ChatPageState extends State<ChatPage>
    with AutomaticKeepAliveClientMixin{//混入，保持状态，切换回来的时候，View不会重置

  //混入需要重写get方法
  @override
  bool get wantKeepAlive => true;

  Widget _buildPopupMenuItem(String imageAss,String title){
    return Row(
      children: [
        Image(image: AssetImage(imageAss),width: 20,),
        Container(width: 20,),
        Text(title,style: TextStyle(color: Colors.white),),
      ],
    );
  }
  
  List <Chat>_datas = [];
  bool _cancleConnect = false;

  @override
  void initState() {
    super.initState();
    
    print('getDatas');
    getDatas().then((List<Chat>datas){
      print('数据来了');

      //没超时，更新数据
      if(!_cancleConnect){
        setState((){
          _datas = datas;
        });
      }
    }).catchError((e){
      print('错误$e');
    }).whenComplete((){
      print('完毕');
    }).timeout(Duration(seconds: 6)).catchError((timeOut){
      _cancleConnect = true;
      //超时之后的请求还是会来的
      print('请求超时 $timeOut');
    });
    
    //  关于Map和json
    // final chat = {
    //   'name':'name',
    //   'message':'message',
    // };
    // // //Map转json
    // final chatJson = json.encode(chat);
    // //Map转json  {"name":"name","message":"message"}
    // print(chatJson);
    // // Map 没有引号  {"name":"name","message":"message"}
    // print(chat);
    // final newChat = json.decode(chatJson);
    // //json 转Map
    // print(newChat);
    // //判断是否Map
    // print(newChat is Map);

    // getDatas();
  }

  Timer _timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
    // print(count);
    // print(Isolate.current.debugName);
    count++;
    if(count > 60){
      timer.cancel();
    }
  });


  void dispose(){
    print('dispose');
    if(_timer != null && _timer.isActive){
      _timer.cancel();
    }
    super.dispose();
  }

  //耗时操作
  Future <List<Chat>> getDatas() async {
    //每次请求时设为false
    _cancleConnect = false;
    //https
    // var url = Uri.parse('http://rap2api.taobao.org/app/mock/303355/api/chat/list');
    //dio
    var url = 'http://rap2api.taobao.org/app/mock/303355/api/chat/list';
    //耗时需要await
    final response = await http.get(url,60);
    // print('response ${response.statusCode}');
    if(response.statusCode == 200){
      // print('toString : ${response.toString()}');
      //https
      //获取并转Map
      // var responseBody = json.decode(response.body);
      //dio
      var responseBody= response.data;
      List<Chat> chatList = responseBody['chat_list'].map<Chat>((item){
        // print(item);
        return Chat.fromJson(item);
        // print(item);
      }).toList();
      // List<Chat> chatList = responseBody['chat_list'].map<Chat>((item) => Chat.fromJson(item)).toList();
      // print(chatList);
      return chatList;
    } else {
      throw Exception('statusCode:${response.statusCode}');
    }
    // print(response.statusCode);
    // print(response.body);
  }

  @override
  Widget build(BuildContext context) {
    //混入需要调
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,//边框栏
        title: Text('微信'),
        backgroundColor: WeChatThemeColor,
        actions: [
          Container(margin: EdgeInsets.only(right: 10),
            child: PopupMenuButton(
              offset: Offset(0,50),
              child: Image(image:AssetImage('images/圆加.png') ,width: 25,),
              itemBuilder: (BuildContext context){
                return <PopupMenuItem<String>>[
                  PopupMenuItem(child:_buildPopupMenuItem('images/发起群聊.png','发起群聊')),
                  PopupMenuItem(child:_buildPopupMenuItem('images/添加朋友.png','添加朋友')),
                  PopupMenuItem(child:_buildPopupMenuItem('images/扫一扫1.png','扫一扫')),
                  PopupMenuItem(child:_buildPopupMenuItem('images/收付款.png','收付款')),
                ];
              }),),

          // GestureDetector(
          //   onTap: (){
          //
          //   },
          //   child: Container(
          //     margin: EdgeInsets.only(right: 10),
          //     child: Image(image: AssetImage('images/圆加.png'),width: 25,),
          //   ),
          // )
        ],
      ),
      body: Container(
        child: _datas.length==0?Center(child: Text('Loading...',)):
        ListView.builder(itemCount: _datas.length + 1,
            itemBuilder: _buildCellForRow),
      )
    );
  }

  Widget _buildCellForRow(BuildContext context, int index){
    if(index == 0){
      return SearchCell(datas: _datas!,);
    }
    //保证从模型数组中正确取出数据!从0开始!
    index--;
    Chat data = _datas[index];
    return ListTile(title: Text(data.name),subtitle: Text(data.message,overflow: TextOverflow.ellipsis,),
        leading: Container(width: 44,height: 44,
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(6.0),
              image: DecorationImage(image: NetworkImage(data.imageUrl))),
        ));
  }
}

/**
 *  Container(
    //异步渲染
    child: FutureBuilder(
    future: getDatas(),
    builder: (BuildContext context, AsyncSnapshot snapshot) {
    //执行多次
    if(snapshot.connectionState == ConnectionState.waiting){
    return Center(child: Text('Loading...'),);
    }
    // print(snapshot.connectionState);
    // print(snapshot.data);
    return  ListView(
    children: snapshot.data.map<Widget>((item){
    return ListTile(title: Text(item.name),
    subtitle: Container(height: 25,
    alignment: Alignment.bottomCenter,
    margin: EdgeInsets.only(right: 10),
    //文字加...
    child: Text(item.message,overflow: TextOverflow.ellipsis,),),
    leading: Container(height: 44,width: 44,
    decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(6),
    image: DecorationImage(image: NetworkImage(item.imageUrl))
    ),
    )
    // CircleAvatar(backgroundImage: NetworkImage(item.imageUrl),),
    );
    }).toList(),);
    },
    )
    ),
 *
 * */

class Chat {

  final String name;
  final String message;
  final String imageUrl;

  Chat({
   required this.name,
   required this.message,
   required this.imageUrl
});

  //factory 工厂构建函数，可以返回已有的（单例）
  factory Chat.fromJson(Map json){
    return Chat(name: json['name'], message: json['message'] , imageUrl:json['imageUrl'] );
  }
}